<?php
// 数据库文件路径
$dbFile = 'cms.db';

// 创建或连接到 SQLite 数据库
$pdo = new PDO('sqlite:' . $dbFile);

// 检查数据库连接
if (!$pdo) {
    die("数据库连接失败！");
}

// 创建表（如果不存在）
$pdo->exec("
CREATE TABLE IF NOT EXISTS posts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    likes INTEGER DEFAULT 0
)");

$pdo->exec("
CREATE TABLE IF NOT EXISTS comments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    post_id INTEGER,
    username TEXT NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (post_id) REFERENCES posts(id)
)");

// 查询所有文章并按创建时间排序（新发布的在最上面）
$posts = $pdo->query("SELECT * FROM posts ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
$comments = $pdo->query("SELECT * FROM comments")->fetchAll(PDO::FETCH_ASSOC);

// 将留言与对应帖子关联
$commentsByPostId = [];
foreach ($comments as $comment) {
    $commentsByPostId[$comment['post_id']][] = $comment;
}
?>

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>乂蛙博客</title>
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <link rel="stylesheet" href="css/mdui.min.css">
<link rel="shortcut icon" href="../sinfrog.cn/img/aifrog.png">
    <style>
        .post-card {
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 16px;
            margin: 10px 0;
            background-color: #fff;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .react-buttons {
            margin-top: 10px;
        }
        .comments {
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #eee;
        }
        .comment {
            margin: 5px 0;
            padding: 5px;
            background-color: #f9f9f9;
            border-radius: 5px;
        }
        .created-at {
            font-size: 0.9em;
            color: #888;
        }
    </style>
</head>
<body class="mdui-theme-primary-blue mdui-theme-accent-blue">
    <div class="mdui-container">
        <h1>乂蛙博客</h1>
        <ul class="mdui-list">
            <?php foreach ($posts as $post): ?>
                <li class="post-card" id="post-<?php echo $post['id']; ?>">
                    <div class="mdui-list-item-content">
                        <strong><?php echo htmlspecialchars($post['title']); ?></strong>
                        <div class="created-at"><?php echo date("Y-m-d H:i:s", strtotime($post['created_at'])); ?></div>
                        <div><?php echo nl2br(htmlspecialchars($post['content'])); ?></div>
                    </div>
                    <div class="react-buttons">
                        <button id="like-button-<?php echo $post['id']; ?>" class="mdui-btn mdui-color-green" onclick="likePost(<?php echo $post['id']; ?>)"><i class="mdui-icon material-icons">&#xe8dc;</i> <?php echo $post['likes']; ?></button>
                        <button class="mdui-btn mdui-color-blue" onclick="showCommentForm(<?php echo $post['id']; ?>)"><i class="mdui-icon material-icons">&#xe0c9;</i> 留言</button>
                    </div>
                    <div class="comments" id="comments-<?php echo $post['id']; ?>">
                        <?php if (isset($commentsByPostId[$post['id']])): ?>
                            <?php foreach ($commentsByPostId[$post['id']] as $comment): ?>
                                <div class="comment">
                                    <strong><?php echo htmlspecialchars($comment['username']); ?></strong>: <?php echo htmlspecialchars($comment['content']); ?>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    <div class="comment-form" id="comment-form-<?php echo $post['id']; ?>" style="display:none;">
                        <input class="mdui-textfield-input" type="text" id="username-<?php echo $post['id']; ?>" placeholder="用户名" />
                        <textarea class="mdui-textfield-input" id="comment-<?php echo $post['id']; ?>" placeholder="留言内容"></textarea>
                        <button onclick="submitComment(<?php echo $post['id']; ?>)" class="mdui-btn mdui-btn-raised">提交留言</button>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
    <script src="js/mdui.min.js"></script>
    <script>
        function likePost(postId) {
            fetch('like.php?id=' + postId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const button = document.getElementById(`like-button-${postId}`);
                        button.innerText = `👍 ${data.likes}`;
                    } else {
                        alert("点赞失败，请稍后再试。");
                    }
                });
        }

        function showCommentForm(postId) {
            const form = document.getElementById(`comment-form-${postId}`);
            form.style.display = form.style.display === "none" ? "block" : "none";
        }

        function submitComment(postId) {
            const username = document.getElementById(`username-${postId}`).value;
            const content = document.getElementById(`comment-${postId}`).value;

            if (username && content) {
                fetch('comment.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ post_id: postId, username: username, content: content })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const commentsDiv = document.getElementById(`comments-${postId}`);
                        const newComment = document.createElement('div');
                        newComment.className = 'comment';
                        newComment.innerHTML = `<strong>${username}</strong>: ${content}`;
                        commentsDiv.appendChild(newComment);

                        // 清空输入框
                        document.getElementById(`username-${postId}`).value = '';
                        document.getElementById(`comment-${postId}`).value = '';
                        showCommentForm(postId); // 隐藏留言框
                    } else {
                        alert("留言失败，请稍后再试。");
                    }
                });
            } else {
                alert("请填写用户名和留言内容。");
            }
        }
    </script>
</body>
</html>